"""Route webhook messages to an amqp queue (AWS Lambda version)."""
from cki_lib import misc
import sentry_sdk
from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration
from sentry_sdk.integrations.logging import ignore_logger

from cki.cki_tools.webhook_receiver import receiver

# ^ absolute import as AWS Lambda does not use python -m

misc.sentry_init(sentry_sdk, integrations=[AwsLambdaIntegration()])

if misc.is_production_or_staging():
    # persistent containers cause dropped connections, which bubble up as
    # [Errno 104] Connection reset by peer, ConnectionResetError, StreamLostError,
    # connection_lost, BlockingConnection.close() on closed connection, ...
    ignore_logger('pika.adapters.utils.io_services_utils')
    ignore_logger('pika.adapters.base_connection')
    ignore_logger('pika.adapters.blocking_connection')

receiver.TRY_ENDLESSLY = True


def _lambda_handler(method, event):
    status_code, message = method(event['headers'],
                                  event['body'].encode('utf8'),
                                  request_args=event.get('queryStringParameters') or {})
    return {'statusCode': status_code, 'body': message}


def gitlab_lambda(event, _):
    """Process a webhook."""
    return _lambda_handler(receiver.gitlab_handler, event)


def sentry_lambda(event, _):
    """Process a webhook."""
    return _lambda_handler(receiver.sentry_handler, event)


def jira_lambda(event, _):
    """Process a webhook."""
    return _lambda_handler(receiver.jira_handler, event)
